package create.singleton;

public class SingletonTest {

	private static int TESTCOUNT = 100;
	private static volatile boolean flag1 = true;
	private static volatile MultipleThreadSingleton instance1;

	private static volatile boolean flag2 = true;
	private static volatile StaticSingleton instance2;

	public static void testSingleThreadSingleton() {
		SingleThreadSingleton inst1 = SingleThreadSingleton.getInstance();
		SingleThreadSingleton inst2 = SingleThreadSingleton.getInstance();
		System.out.println("单线程单例测试结果：" + (inst1 == inst2));
	}

	public static void testMultipleThreadSingleton() throws InterruptedException {
		for (int i = 0; i < TESTCOUNT; i++) {
			final int j = i;
			Thread thread = new Thread() {
				public void run() {
					System.out.println("多线程单例测试开始：" + j);
					MultipleThreadSingleton inst1 = MultipleThreadSingleton.getInstance();
					if (instance1 == null) {
						instance1 = inst1;
						return;
					}
					if (instance1 != inst1) {
						flag1 = false;
					}
				}
			};
			thread.join();
			thread.start();
		}
		System.out.println("多线程单例测试结果：" + flag1);
	}

	public static void testStaticSingleton() throws InterruptedException {
		for (int i = 0; i < TESTCOUNT; i++) {
			final int j = i;
			Thread thread = new Thread() {
				public void run() {
					System.out.println("静态多线程单例测试开始：" + j);
					StaticSingleton inst2 = StaticSingleton.getInstance();
					if (instance2 == null) {
						instance2 = inst2;
						return;
					}
					if (instance2 != inst2) {
						flag2 = false;
					}
				}
			};
			thread.join();
			thread.start();
		}
		System.out.println("静态多线程单例测试结果：" + flag2);
	}

	public static void main(String[] args) throws InterruptedException {
		testSingleThreadSingleton();
		testMultipleThreadSingleton();
		testStaticSingleton();
	}

}
